<?php
/**
 * Description: 支付宝手机wap支付异步回调处理
 * User: devforma
 * Date: 15/6/3
 * Time: 14:27
 */

require PUBLIC_DIR . '/payment/includes/Alipay.class.php';
require PUBLIC_DIR . '/payment/includes/OrderProcess.class.php';

class AlipayDirectWebNotifyUrl implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        $payment = new Alipay();

        if ($payment->checkSign('md5', $queryArgs, true)) { //验证签名

            //商户订单号
            $outTradeNo = $_POST['out_trade_no'];
            //支付宝交易号
            $alipayTradeNo = $_POST['trade_no'];
            //交易状态
            $tradeStatus = $_POST['trade_status'];
            //买家支付宝账号
            $alipayUser = empty($_POST['buyer_email']) ? '' : $_POST['buyer_email'];

            if ($tradeStatus == 'TRADE_FINISHED' || $tradeStatus == 'TRADE_SUCCESS') { //支付成功
                $orderProcess = new OrderProcess($outTradeNo, $alipayTradeNo, $alipayUser, 'alipay');

                if ($orderProcess->isExists() && !$orderProcess->isPurchased()) {
                    $orderProcess::clearCache($outTradeNo);

                    if (!$orderProcess->finish()) return 'fail';

                    return 'success';
                }
            }
        }

        return 'fail';
    }
}